//
//  HMComposeViewController.swift
//  大深圳微博01
//
//  Created by shenzhenIOS on 16/4/18.
//  Copyright © 2016年 shenzhenIOS. All rights reserved.
//

import UIKit

import SVProgressHUD

class HMComposeViewController: UIViewController {
    
    private var maxOfLength = 25
    
    // 照片选择view是否显示
    private var isShowPhotoSelectorView = false

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        
        prepareUI()
        
        // 监听键盘frame的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("willChangeFrame:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 在这里让键盘处理啊,toolBar会由奇怪的动画
//        textView.becomeFirstResponder()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 如果照片选择view没有显示才需要主动弹出键盘
        if !isShowPhotoSelectorView {
            textView.becomeFirstResponder()
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /*
    notification: NSConcreteNotification 0x7ff980bcd510 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        UIKeyboardIsLocalUserInfoKey = 1;
    }}
    
    UIKeyboardWillChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardIsLocalUserInfoKey = 1;
    }}
    */
    @objc private func willChangeFrame(notification: NSNotification) {
//        HMPrint("notification: \(notification)")
        // 键盘frame的值
        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        let y = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        
        // 动画
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(y)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    private func prepareUI() {
        setupNavigationBar()
        
        setupTextView()
        setupPhotoSelectorView()
        setupToolBar()
        setupLengthTipLabel()
    }
    
    /// 设置照片选择器的view
    private func setupPhotoSelectorView() {
        // 将照片选择控制器的view添加到发微博控制器的view里面子
        let photoSelectorView = photoSelectorVC.view
        self.view.addSubview(photoSelectorView)
        
        // 当一个控制器的view成为另一个控制器的view的子view,那么这个控制器页最好成为另外一个控制器的子控制器
        self.addChildViewController(photoSelectorVC)
        
        // 添加约束
        photoSelectorView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(UIScreen.mainScreen().bounds.height * 0.6)
            make.height.equalTo(UIScreen.mainScreen().bounds.height * 0.6)
        }
    }
    
    private func setupLengthTipLabel() {
        view.addSubview(lengthTipLabel)
        
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top).offset(-4)
            make.trailing.equalTo(toolBar).offset(-4)
        }
    }
    
    /// 设置textView
    private func setupTextView() {
        // 1.添加控件
        view.addSubview(textView)
        
        // 2.添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        
        /// 让控制器里面的view里面的内容往下偏移
        /*
            1.UIScrollView或子类
            2.在导航控制器,tabBarControl里面
            3.UIScrollView或子类必须是控制器的view,或者UIScrollView或子类是控制器的view第一个子view,或者UIScrollView或子类是控制器的view第一个子view的第一个子view
        */
//        self.automaticallyAdjustsScrollViewInsets = true
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        // 添加控件
        view.addSubview(toolBar)
        
        // 添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        // 每个item对应的图片名称
        let itemSettings = [
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        
        var items = [UIBarButtonItem]()
        var index = 0
        // 遍历数组获取每个item的信息
        for dict in itemSettings {
            // 获取图片名称
            let iamgeName = dict["imageName"]!
            
            // 获取点击事件的名称
            let action = dict["action"]!
            
            // 创建UIBarButtonItem, 里面包一个按钮
            let item = UIBarButtonItem(imageName: iamgeName, target: self, action: Selector(action))
            items.append(item)
            
            let button = item.customView as! UIButton
            button.tag = index
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            index++
        }
        
        // 删除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("sendStatus"))
        
        // 右边按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
    }
    
    /// 设置TitleView
    private func setupTitleView() {
//        navigationItem.titleView
        let prefix = "发微博"
        if let name = HMUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            // 有名字 \n 换行
            let title = prefix + "\n" + name
            
            // 创建label
            let titleLabel = UILabel()
            titleLabel.numberOfLines = 0
            titleLabel.textAlignment = NSTextAlignment.Center
            titleLabel.textColor = UIColor.blackColor()
            titleLabel.font = UIFont.systemFontOfSize(HMWelcomeLabelFontSize)
            
            // 使用属性文本
            let attrStringM = NSMutableAttributedString(string: title)
            
            let range = (title as NSString).rangeOfString(name)
            // 添加属性
            // NSForegroundColorAttributeName: 文字的前景颜色
            attrStringM.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            attrStringM.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
            
            titleLabel.attributedText = attrStringM
            
            // label的size会根据label里面的文本内容自己计算
            titleLabel.sizeToFit()
            
            navigationItem.titleView = titleLabel
        } else {
            // 没有名字
            navigationItem.title = prefix
        }
    }
    
    // MARK: - 按钮点击事件
    @objc private func picture() {
//        print("图片")
        
        isShowPhotoSelectorView = true
        // 将照片选择界面动画上来
        photoSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(0)
        }
        
        UIView.animateWithDuration(HMDefautlAnimDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        // 让键盘退下
        textView.resignFirstResponder()
    }
    
    @objc private func trend() {
        print("#")
    }

    
    @objc private func mention() {
        print("@")
    }

    
    @objc private func emoticon(button: UIButton) {
        print("表情")
        // 切换键盘,不是赋值后就立马切换, 在键盘弹出之前 textView.inputView == nil, 就会用系统的键盘, textView.inputView != nil, 就用设置的键盘
        
        // 设置toolBar的按钮
        var normalImage: UIImage?
        var highlightedImage: UIImage?
        
        // 退出键盘
        textView.resignFirstResponder()
        
        // 之前是系统键盘就换成我们的键盘,之前是我们的键盘就切换到系统键盘
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        
        if textView.inputView == nil {
            // 系统键盘
            normalImage = UIImage(named: "compose_emoticonbutton_background")
            highlightedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")
        } else {
            // 自定义键盘
            normalImage = UIImage(named: "compose_keyboardbutton_background")
            highlightedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")
        }
        
        button.setImage(normalImage, forState: UIControlState.Normal)
        button.setImage(highlightedImage, forState: UIControlState.Highlighted)
        
        // 等0.25，先让键盘动画下去,在弹出来
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
    }

    
    @objc private func add() {
        print("加号")
    }

//    @objc private func didClickItem(button: UIButton) {
//        switch button.tag {
//        case 0:
//            print("图片")
//        case 1:
//            print("#")
//        case 2:
//            print("@")
//        case 3:
//            print("表情")
//        case 4:
//            print("加号")
//        default:
//            print("没有按钮")
//        }
//    }
    
    @objc private func close() {
        SVProgressHUD.dismiss()
        // textView取消第一相应者,键盘就会退下
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendStatus() {
        // 发布微博
        let text = textView.emoticonText()
        
        // 判断是否超出了长度
        let last = maxOfLength - text.characters.count
        if last < 0 {
            SVProgressHUD.showErrorWithStatus("超出最大长度")
            return
        }
        
        // 提示正在发微博
        SVProgressHUD.showWithStatus("正在发布微博...")
        
        // 去照片选择器里面拿图片
        let image = photoSelectorVC.photos.first
        
        HMStatusViewModel.sharedInstance.sendStatus(text, image: image) { (error) -> () in
            if error != nil {
                HMPrint("发布微博失败: \(error)")
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                // 发布微博成功了, 关闭控制器
                self.close()
            })
        }
    }
    
    // MARK: - 懒加载
    /// toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    /// textView
    private lazy var textView: HMPlaceholderTextView = {
        let tv = HMPlaceholderTextView()
        
        // 设置
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.blackColor()

//        tv.text = "分享新鲜事......"
        
        // 设置占位文本
        tv.placeholder = "我是占位文本"
        
        // 监听textView文字的改变
        tv.delegate = self
        
        // 垂直弹簧效果
        tv.alwaysBounceVertical = true
        
        // 当拖拽textView就会关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return tv
    }()
    
    /// 表情键盘的view
    private lazy var emoticonKeyboard: HMEmoticonKeyboard = {
        let keyboard = HMEmoticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    /// 长度提示label
    private lazy var lengthTipLabel: UILabel = {
        let label = UILabel(fontSize: 10, textColor: UIColor.lightGrayColor())
        
        label.text = String(self.maxOfLength)
        label.sizeToFit()
        
        return label
    }()
    
    /// 照片选择控制器
    private lazy var photoSelectorVC: HMPhotoSelectorController = HMPhotoSelectorController()
}

extension HMComposeViewController: UITextViewDelegate {
    // 文字改变
    func textViewDidChange(textView: UITextView) {
        // 设置导航栏右边按钮的可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 已经输入文本
        let text = textView.emoticonText()
        
        // 计算剩余文本的长度
        let last = maxOfLength - text.characters.count
        
        lengthTipLabel.text = String(last)
        
        let color = last < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        lengthTipLabel.textColor = color
    }
}